const std = @import("std");
const mem = @import("memory.zig");
const caps = @import("caps.zig");
const trap = @import("trap.zig");
const api = @import("api.zig");

// 总线类型枚举
pub const BusType = enum(u8) {
    unknown,
    pci,
    usb,
    i2c,
    spi,
    isa,
    acpi,
    max,
};

// 设备状态枚举
pub const DeviceState = enum(u8) {
    unknown,
    disconnected,
    connected,
    initialized,
    suspended,
    error,
};

// 设备信息结构
pub const DeviceInfo = struct {
    id: u64,
    vendor_id: u32,
    device_id: u32,
    class_id: u32,
    subclass_id: u32,
    prog_if: u32,
    bus_type: BusType,
    bus_info: *anyopaque,
};

// 驱动接口结构
pub const DriverInterface = struct {
    name: []const u8,
    description: []const u8,
    version: u32,
    init: *const fn(allocator: std.mem.Allocator, driver_data: *anyopaque) bool,
    deinit: *const fn(driver_data: *anyopaque) void,
    probe: *const fn(device_info: *DeviceInfo) bool,
    remove: *const fn(device_id: u64) void,
    ioctl: *const fn(device_id: u64, cmd: u32, data: *anyopaque, size: u64) isize,
};

// 设备实例结构
pub const Device = struct {
    id: u64,
    info: DeviceInfo,
    driver: *DriverInterface,
    driver_data: *anyopaque,
    capabilities: []api.CapabilityId,
    state: DeviceState,
};

// 驱动管理器结构
pub const DriverManager = struct {
    allocator: std.mem.Allocator,
    drivers: std.ArrayList(*DriverInterface),
    devices: std.ArrayList(Device),
    next_device_id: u64,
    next_driver_id: u64,
    memory_manager: *mem.MemoryManager,
    capability_manager: *caps.CapabilityManager,
    trap_handler: *trap.TrapHandler,

    // 初始化驱动管理器
    pub fn init(
        allocator: std.mem.Allocator,
        memory_manager: *mem.MemoryManager,
        capability_manager: *caps.CapabilityManager,
        trap_handler: *trap.TrapHandler
    ) !DriverManager {
        var drivers = std.ArrayList(*DriverInterface).init(allocator);
        var devices = std.ArrayList(Device).init(allocator);

        return DriverManager {
            .allocator = allocator,
            .drivers = drivers,
            .devices = devices,
            .next_device_id = 1,
            .next_driver_id = 1,
            .memory_manager = memory_manager,
            .capability_manager = capability_manager,
            .trap_handler = trap_handler,
        };
    }

    // 清理驱动管理器
    pub fn deinit(self: *DriverManager) void {
        // 卸载所有驱动
        while (self.drivers.items.len > 0) {
            const driver = self.drivers.pop();
            _ = self.unload_driver(driver);
        }

        // 清理设备列表
        self.devices.deinit();
        self.drivers.deinit();
    }

    // 加载驱动
    pub fn load_driver(self: *DriverManager, driver: *DriverInterface) !bool {
        // 检查驱动是否已经加载
        for (self.drivers.items) |loaded_driver| {
            if (std.mem.eql(u8, driver.name, loaded_driver.name)) {
                return false; // 驱动已加载
            }
        }

        // 添加驱动到驱动列表
        try self.drivers.append(driver);

        // 为驱动分配必要的能力
        const driver_cap = try self.capability_manager.create_capability(
            caps.CapabilityType.driver,
            caps.CapabilityPermission.all,
            self.next_driver_id
        );
        self.next_driver_id += 1;

        // 尝试初始化驱动
        var driver_data: ?*anyopaque = null;
        if (!driver.init(self.allocator, driver_data)) {
            // 初始化失败，移除驱动
            _ = self.unload_driver(driver);
            return false;
        }

        return true;
    }

    // 卸载驱动
    pub fn unload_driver(self: *DriverManager, driver: *DriverInterface) bool {
        // 查找驱动在列表中的索引
        var driver_index: ?usize = null;
        for (self.drivers.items, 0..) |loaded_driver, index| {
            if (loaded_driver == driver) {
                driver_index = index;
                break;
            }
        }

        if (driver_index == null) {
            return false; // 驱动未加载
        }

        // 移除所有使用该驱动的设备
        var i: usize = 0;
        while (i < self.devices.items.len) {
            if (self.devices.items[i].driver == driver) {
                self.remove_device(self.devices.items[i].id);
            } else {
                i += 1;
            }
        }

        // 从列表中移除驱动
        _ = self.drivers.swapRemove(driver_index.?);

        return true;
    }

    // 注册设备
    pub fn register_device(self: *DriverManager, device_info: *DeviceInfo) !u64 {
        // 为设备分配ID
        const device_id = self.next_device_id;
        self.next_device_id += 1;
        device_info.id = device_id;

        // 查找适合的驱动
        for (self.drivers.items) |driver| {
            if (driver.probe(device_info)) {
                // 为设备分配必要的能力
                const mem_cap = try self.capability_manager.create_capability(
                    caps.CapabilityType.memory,
                    caps.CapabilityPermission.all,
                    device_id
                );
                const io_cap = try self.capability_manager.create_capability(
                    caps.CapabilityType.io,
                    caps.CapabilityPermission.all,
                    device_id
                );
                const irq_cap = try self.capability_manager.create_capability(
                    caps.CapabilityType.interrupt,
                    caps.CapabilityPermission.all,
                    device_id
                );

                const capabilities = try self.allocator.dupe(api.CapabilityId, &[_]api.CapabilityId{mem_cap, io_cap, irq_cap});

                // 创建设备实例
                var device = Device{
                    .id = device_id,
                    .info = device_info.*,
                    .driver = driver,
                    .driver_data = undefined, // 驱动在probe时会设置
                    .capabilities = capabilities,
                    .state = DeviceState.initialized,
                };

                // 添加设备到设备列表
                try self.devices.append(device);

                return device_id;
            }
        }

        return error.NoSuitableDriver;
    }

    // 移除设备
    pub fn remove_device(self: *DriverManager, device_id: u64) void {
        // 查找设备在列表中的索引
        var device_index: ?usize = null;
        for (self.devices.items, 0..) |device, index| {
            if (device.id == device_id) {
                device_index = index;
                break;
            }
        }

        if (device_index == null) {
            return; // 设备不存在
        }

        const device = &self.devices.items[device_index.?];

        // 调用驱动的移除函数
        device.driver.remove(device_id);

        // 释放设备的能力
        for (device.capabilities) |cap_id| {
            self.capability_manager.release_capability(cap_id);
        }

        // 释放能力数组
        self.allocator.free(device.capabilities);

        // 从列表中移除设备
        _ = self.devices.swapRemove(device_index.?);
    }

    // 通过ID获取设备
    pub fn get_device(self: *DriverManager, device_id: u64) ?*Device {
        for (self.devices.items) |*device| {
            if (device.id == device_id) {
                return device;
            }
        }
        return null;
    }

    // 列出所有加载的驱动
    pub fn list_drivers(self: *DriverManager) []*DriverInterface {
        return self.drivers.items;
    }

    // 列出所有注册的设备
    pub fn list_devices(self: *DriverManager) []Device {
        return self.devices.items;
    }

    // 向设备发送控制命令
    pub fn ioctl(self: *DriverManager, device_id: u64, cmd: u32, data: *anyopaque, size: u64) isize {
        const device = self.get_device(device_id) orelse return -1;
        return device.driver.ioctl(device_id, cmd, data, size);
    }

    // 为驱动注册中断处理程序
    pub fn register_irq_handler(self: *DriverManager, cap_id: api.CapabilityId, irq: u32, handler: u64) bool {
        // 检查能力权限
        const cap = self.capability_manager.get_capability(cap_id) orelse return false;
        if (!self.capability_manager.check_permission(cap, caps.CapabilityPermission.write)) {
            return false;
        }

        // 注册中断处理程序
        return self.trap_handler.setInterruptHandler(irq, handler);
    }

    // 为驱动注销中断处理程序
    pub fn unregister_irq_handler(self: *DriverManager, cap_id: api.CapabilityId, irq: u32) bool {
        // 检查能力权限
        const cap = self.capability_manager.get_capability(cap_id) orelse return false;
        if (!self.capability_manager.check_permission(cap, caps.CapabilityPermission.write)) {
            return false;
        }

        // 注销中断处理程序
        return self.trap_handler.clearInterruptHandler(irq);
    }

    // 为驱动发送中断结束信号
    pub fn send_eoi(self: *DriverManager, cap_id: api.CapabilityId, irq: u32) void {
        // 检查能力权限
        const cap = self.capability_manager.get_capability(cap_id) orelse return;
        if (!self.capability_manager.check_permission(cap, caps.CapabilityPermission.write)) {
            return;
        }

        // 发送EOI信号
        self.trap_handler.sendEOI(irq);
    }
};

// 全局驱动管理器实例
var global_driver_manager: ?*DriverManager = null;

// 初始化全局驱动管理器
export fn kuya_driver_manager_init(
    memory_manager_ptr: [*c]u8,
    capability_manager_ptr: [*c]u8,
    trap_handler_ptr: [*c]u8
) bool {
    if (global_driver_manager != null) {
        return true; // 已经初始化
    }

    const memory_manager = @ptrCast(*mem.MemoryManager, memory_manager_ptr);
    const capability_manager = @ptrCast(*caps.CapabilityManager, capability_manager_ptr);
    const trap_handler = @ptrCast(*trap.TrapHandler, trap_handler_ptr);

    const allocator = memory_manager.allocator;

    var driver_manager = allocator.create(DriverManager) catch return false;
    driver_manager.* = DriverManager.init(
        allocator,
        memory_manager,
        capability_manager,
        trap_handler
    ) catch return false;

    global_driver_manager = driver_manager;
    return true;
}

// 清理全局驱动管理器
export fn kuya_driver_manager_deinit() void {
    if (global_driver_manager == null) {
        return;
    }

    const driver_manager = global_driver_manager.?;
    const allocator = driver_manager.allocator;

    driver_manager.deinit();
    allocator.destroy(driver_manager);
    global_driver_manager = null;
}

// 加载驱动
export fn kuya_driver_load(
    driver_ptr: [*c]u8
) bool {
    if (global_driver_manager == null) {
        return false;
    }

    const driver = @ptrCast(*DriverInterface, driver_ptr);
    return global_driver_manager.?.load_driver(driver) catch false;
}

// 卸载驱动
export fn kuya_driver_unload(
    driver_ptr: [*c]u8
) bool {
    if (global_driver_manager == null) {
        return false;
    }

    const driver = @ptrCast(*DriverInterface, driver_ptr);
    return global_driver_manager.?.unload_driver(driver);
}

// 注册设备
export fn kuya_device_register(
    device_info_ptr: [*c]u8
) u64 {
    if (global_driver_manager == null) {
        return 0;
    }

    const device_info = @ptrCast(*DeviceInfo, device_info_ptr);
    return global_driver_manager.?.register_device(device_info) catch 0;
}

// 移除设备
export fn kuya_device_remove(
    device_id: u64
) void {
    if (global_driver_manager == null) {
        return;
    }

    global_driver_manager.?.remove_device(device_id);
}

// 设备控制
export fn kuya_device_ioctl(
    device_id: u64,
    cmd: u32,
    data_ptr: [*c]u8,
    size: u64
) isize {
    if (global_driver_manager == null) {
        return -1;
    }

    const data = @ptrCast(*anyopaque, data_ptr);
    return global_driver_manager.?.ioctl(device_id, cmd, data, size);
}

// 注册中断处理程序
export fn kuya_driver_register_irq_handler(
    cap_id: api.CapabilityId,
    irq: u32,
    handler: u64
) bool {
    if (global_driver_manager == null) {
        return false;
    }

    return global_driver_manager.?.register_irq_handler(cap_id, irq, handler);
}

// 注销中断处理程序
export fn kuya_driver_unregister_irq_handler(
    cap_id: api.CapabilityId,
    irq: u32
) bool {
    if (global_driver_manager == null) {
        return false;
    }

    return global_driver_manager.?.unregister_irq_handler(cap_id, irq);
}

// 发送中断结束信号
export fn kuya_driver_send_eoi(
    cap_id: api.CapabilityId,
    irq: u32
) void {
    if (global_driver_manager == null) {
        return;
    }

    global_driver_manager.?.send_eoi(cap_id, irq);
}